#pragma once
#include <iostream>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "log.hpp"
#include "InetAddr.hpp"

using func_t = std::function<void(int, const std::string&, InetAddr&)>;
using namespace MyLog;
class UDPsocket
{
public:
    UDPsocket(u_int16_t port, func_t func)
        : _port(port),
          _isrunning(false),
          _func(func)
    {
    }
    ~UDPsocket() {}

    void Init()
    {
        // 1.创建socket
        int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(sockfd < 0){
            LOG(loglevel::FATAL) << "create socket fail";
            exit(1);
        }
        _sockfd = sockfd;
        LOG(loglevel::INFO) << "create socket success";

        // 2.绑定socket
        struct sockaddr_in addr;
        bzero(&addr, sizeof(addr));
        addr.sin_family = AF_INET;
        addr.sin_port = htons(_port);
        addr.sin_addr.s_addr = INADDR_ANY;
        int n = bind(_sockfd, (const struct sockaddr*)&addr, sizeof(addr));
        if(n < 0){
            LOG(loglevel::FATAL) << "bind socket fail";
            exit(2);
        }
        LOG(loglevel::INFO) << "bind socket success";
    }

    void Start()
    {
        _isrunning = true;
        while(true){
            // 1.服务端从网络中，获取客户端发来的信息
            char buffer[1024];
            struct sockaddr_in client;
            socklen_t client_size = sizeof(client);
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&client, &client_size);
            if(n > 0){
                // 2.服务器将收到的消息路由给其他在线用户
                buffer[n] = 0;
                InetAddr cli(client);
                _func(_sockfd, buffer, cli);
            }
        }
    }

private:
    u_int16_t _port; // 端口号
    int _sockfd;     // 标识socket的文件描述符
    bool _isrunning;
    func_t _func;    // 回调方法
};